package com.wzy.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzy.base.exception.CustomException;
import com.wzy.base.model.PageParams;
import com.wzy.base.model.PageResult;
import com.wzy.content.mapper.*;
import com.wzy.content.model.dto.*;
import com.wzy.content.model.po.*;
import com.wzy.content.service.CourseBaseInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author wzy
 * @Date 2023/12/25 21:56
 * @description: 课程基本信息管理业务实现
 */
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CoursePublishPreMapper coursePublishPreMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;
    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    @Autowired
    private CourseAuditMapper courseAuditMapper;
    /**
     * 课程分页查询
     *
     * @param pageParams           分页参数
     * @param queryCourseParamsDto 查询条件
     * @return
     */
    @Override
    public PageResult<CourseBaseInfoDto> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //构建插叙条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件根据课程名称进行查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        //构建查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        //构建查询条件，根据课程发布状态查询
        //根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());


        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        //获取数据列表
        List<CourseBase> records = pageResult.getRecords();
        List<CourseBaseInfoDto> courseBaseInfoDtos = records.stream().map(item -> {
            CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
            BeanUtils.copyProperties(item, courseBaseInfoDto);
            CourseMarket courseMarket = courseMarketMapper.selectById(item.getId());
            if(courseMarket!=null){
                String charge = courseMarket.getCharge();//收费规则
                courseBaseInfoDto.setCharge(charge);
            }
            return courseBaseInfoDto;
        }).collect(Collectors.toList());
        //获取数据总数
        long total = pageResult.getTotal();
        return new PageResult<>(courseBaseInfoDtos,total, pageParams.getPageNo(), pageParams.getPageSize());
    }

    /**
     * 新增课程基本信息
     * @param companyId 教学机构id
     * @param addCourseDto 课程基本信息
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto addCourserBaseInfo(Long companyId, AddCourseDto addCourseDto) {
//        //合法性校验
//        if(StringUtils.isBlank(addCourseDto.getName())){
//            throw new CustomException("课程名称不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getUsers())){
//            throw new CustomException("使用人群不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getMt())){
//            throw new CustomException("课程大分类不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getSt())){
//            throw new CustomException("课程小名称不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getGrade())){
//            throw new CustomException("课程等级不能为空");
//        }
//        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
//            throw new CustomException("教育模式不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getCharge())){
//            throw new CustomException("收费规则不能为空");
//        }
        //新增对象
        CourseBase courseBaseNew = new CourseBase();
        BeanUtils.copyProperties(addCourseDto,courseBaseNew);
        //设置审核状态
        courseBaseNew.setAuditStatus("202002");//未提交
        //设置发布状态
        courseBaseNew.setStatus("203001");//未发布
        //机构id
        courseBaseNew.setCompanyId(companyId);
        //添加时间
        courseBaseNew.setCreateDate(LocalDateTime.now());
        //插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBaseNew);
        if(insert<=0){
            throw new CustomException("新增课程失败");
        }

        //向课程营销表保存课程营销信息
        //课程营销信息对象
        CourseMarket courseMarket = new CourseMarket();
        //就页面输入的数据copy到courseMarket
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        Long courseId = courseBaseNew.getId();//主键id
        courseMarket.setId(courseId);
        //保存营销信息
        int i = saveCourseMarket(courseMarket);
        if(i<=0){
            throw new CustomException("保存课程营销信息失败");
        }
        //查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseId);
    }

    /**
     * 根据课程id查询课程基本信息
     * @param courseId 课程id
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfoById(Long courseId) {
        return getCourseBaseInfo(courseId);
    }

    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBaseInfo(Long companyId,EditCourseDto editCourseDto) {
        Long courseId = editCourseDto.getId();//课程id
        CourseBase courseBaseInfo = courseBaseMapper.selectById(courseId);
        if(courseBaseInfo==null){
            throw new CustomException("课程不存在");
        }
        if(!courseBaseInfo.getCompanyId().equals(companyId)){
            throw new CustomException("本机构只能修改本机构的课程");
        }
        //封装基本信息的数据
        BeanUtils.copyProperties(editCourseDto,courseBaseInfo);
        courseBaseInfo.setChangeDate(LocalDateTime.now());

        //修改课程基本信息数据
        courseBaseMapper.updateById(courseBaseInfo);

        //封装营销数据的信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        saveCourseMarket(courseMarket);
        //查询修改后的课程信息返回
        return this.getCourseBaseInfo(courseId);
    }

    @Transactional
    @Override
    public void deleteCourseInfo(Long companyId, Long courseId) {
        //根据课程id查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (!companyId.equals(courseBase.getCompanyId())){
            throw new CustomException("只允许删除本机构的课程");
        }
        //课程的审核状态为未提交时方可删除。
        String auditStatus = courseBase.getAuditStatus();//审核状态
        if(!auditStatus.equals("202002")){
            throw new CustomException("审核状态为未提交时方可删除");
        }
        //删除课程需要删除课程相关的基本信息
        courseBaseMapper.deleteById(courseId);
        // 删除营销信息
        courseMarketMapper.deleteById(courseId);
        // 删除课程计划
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        teachplanMapper.delete(queryWrapper);
        //删除课程对应的视频信息
        LambdaQueryWrapper<TeachplanMedia> mediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        mediaLambdaQueryWrapper.eq(TeachplanMedia::getCourseId,courseId);
        teachplanMediaMapper.delete(mediaLambdaQueryWrapper);
        // 删除课程教师信息
        LambdaQueryWrapper<CourseTeacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherLambdaQueryWrapper.eq(CourseTeacher::getCourseId, courseId);
        courseTeacherMapper.delete(teacherLambdaQueryWrapper);
    }

    /**
     * 查询待审核的课程数量
     * @return
     */
    @Override
    public Integer getAuditCourseNum() {
        LambdaQueryWrapper<CourseBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseBase::getAuditStatus,"202003");//已提交审核
        Integer count = courseBaseMapper.selectCount(lambdaQueryWrapper);
        return count;
    }

    /**
     * 查询待审核课程列表
     * @param pageParams 分页参数
     * @param queryCourseParamsDto 查询条件
     * @return
     */
    @Override
    public PageResult<CourseBaseInfoDto> queryAuthCourseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //构建插叙条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件根据课程名称进行查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        //构建查询条件，根据课程发布状态查询
        //根据课程发布状态查询
        queryWrapper.eq(CourseBase::getAuditStatus,"202003");

        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        //获取数据列表
        List<CourseBase> records = pageResult.getRecords();
        List<CourseBaseInfoDto> courseBaseInfoDtos = records.stream().map(item -> {
            CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
            BeanUtils.copyProperties(item, courseBaseInfoDto);
            CourseMarket courseMarket = courseMarketMapper.selectById(item.getId());
            if(courseMarket!=null){
                String charge = courseMarket.getCharge();//收费规则
                courseBaseInfoDto.setCharge(charge);
            }
            return courseBaseInfoDto;
        }).collect(Collectors.toList());
        //获取数据总数
        long total = pageResult.getTotal();
        return new PageResult<>(courseBaseInfoDtos,total, pageParams.getPageNo(), pageParams.getPageSize());
    }

    /**
     * 审核课程
     * @param auditCourseDto 审核参数
     */
    @Transactional
    @Override
    public void auditCourseById(AuditCourseDto auditCourseDto) {
        Long courseId = auditCourseDto.getCourseId();//课程id
        Boolean flag = auditCourseDto.getRegion();//是否审核通过 true为通过
        if(courseId==null|| flag ==null){
            throw new CustomException("审核课程为空");
        }
        //课程审核后更新课程基本信息表的审核状态
        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CourseBase::getId,courseId);
        if(flag){
            //审核通过
            updateWrapper.set(CourseBase::getAuditStatus,"202004");
        }else{
            updateWrapper.set(CourseBase::getAuditStatus,"202001");
        }
        courseBaseMapper.update(null,updateWrapper);
        // 更新课程预发布表的审核状态，
        LambdaUpdateWrapper<CoursePublishPre> publishPreLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        publishPreLambdaUpdateWrapper.eq(CoursePublishPre::getId,courseId);
        if(flag){
            //审核通过
            publishPreLambdaUpdateWrapper.set(CoursePublishPre::getStatus,"202004");
            coursePublishPreMapper.update(null,publishPreLambdaUpdateWrapper);
        }else{
            //审核不通过将此条记录从预发布表删除
            coursePublishPreMapper.deleteById(courseId);

        }
        // 并将审核结果写入课程审核记录。
        CourseAudit courseAudit = new CourseAudit();
        courseAudit.setAuditDate(LocalDateTime.now());
        courseAudit.setAuditMind(auditCourseDto.getReason());
        courseAudit.setCourseId(courseId);
        if(flag){
            courseAudit.setAuditStatus("202004");
        }else{
            courseAudit.setAuditStatus("202001");
        }
        courseAuditMapper.insert(courseAudit);

    }

    //课程营销信息 存在就更新，不存在就新增
    private int saveCourseMarket(CourseMarket courseMarket){
        //参数的合法性校验
        //收费规则
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new CustomException("收费规则没有选择");
        }
        //收费规则为收费
        if(charge.equals("201001")){
            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue()<=0 || courseMarket.getOriginalPrice() == null || courseMarket.getOriginalPrice().floatValue()<=0){
                throw new CustomException("课程为收费价格不能为空且必须大于0");
            }
        }
        //根据id从营销表中查询对应的营销信息
        CourseMarket courseMarketInfo = courseMarketMapper.selectById(courseMarket.getId());
        if(courseMarketInfo==null){//不存在则插入
            return courseMarketMapper.insert(courseMarket);
        }else{
            //存在就更新
            BeanUtils.copyProperties(courseMarket,courseMarketInfo);//属性copy 将新的属性更新
//            courseMarketInfo.setId(courseMarket.getId());
            return courseMarketMapper.updateById(courseMarketInfo);//修改
        }
    }

    //根据课程id查询课程基本信息，包括基本信息和营销信息
    private CourseBaseInfoDto getCourseBaseInfo(Long id){
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        //查询出课程基本信息
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if(courseBase==null){
            return null;
        }
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        //查询出课程对应的营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if(courseMarket!=null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询课程分类表，查询编号对应的分类名称
        CourseCategory courseCategoryMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryMt.getName());//大分类（一级分类）
        CourseCategory courseCategorySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategorySt.getName());//小分类（二级分类）

        return courseBaseInfoDto;
    }

}
